<?php
/**
 * Created by PhpStorm.
 * User: zhongyb
 * Date: 16-9-23
 * Time: 下午3:50
 */

namespace console\controllers;

use common\services\common\MyscrmDatabaseInstanceConfigService;
use common\services\common\MyscrmOrganizationService;

use common\support\ServiceHelper;
use Exception;
use yii;
use yii\console\Controller;

/**
 * Class XunjianJobController
 * @package  console\controllers
 * @proerpty MyscrmDatabaseInstanceConfigEntity $defaultXunjianDb
 */
class XunjianJobController extends Controller
{
    //默认巡检数据库实例设置在 配置库configsettings中设置
    private $defaultXunjianDb;

    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);

        $default_xunjian_database_instance_id = ServiceHelper::getConfigByKey('DEFAULT_XUNJIAN_DATABASE_INSTANCE_ID');
        /* @var $databaseInstanceConfigService MyscrmDatabaseInstanceConfigService */
        $databaseInstanceConfigService = Yii::createObject(MyscrmDatabaseInstanceConfigService::className());
        $databaseInstance = $databaseInstanceConfigService->getConfigById($default_xunjian_database_instance_id);

        if (empty($databaseInstance)) {
            throw new Exception("找不到默认的巡检DB");
        }

        $this->defaultXunjianDb = $databaseInstance;

    }

    /**
     * 创建巡检数据库
     * @param      $orgCode
     * @param bool $forceInit
     * @throws yii\base\Exception
     */
    public function actionInit($orgCode, $forceInit = false)
    {
        /** @var MyscrmOrganizationService $myscrmOrganizationService */
        $myscrmOrganizationService = Yii::createObject(MyscrmOrganizationService::className());

        $orgCodes = explode(',', $orgCode);
        foreach ($orgCodes as $code) {
            try {
                $myscrmOrganizationService->oldOrganizationInitProcess($code, $forceInit);
            } catch (\Exception $e) {
                $myscrmOrganizationService->oldOrganizationInitProcess($code, true);
            }
        }
    }

}